package com.example.bit.spring_project.controller;

import com.example.bit.spring_project.Massage.Massage;
import com.example.bit.spring_project.model.MassageInfo;
import com.example.bit.spring_project.service.MassageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MassageController {

    @Autowired
    MassageService service;

    /**
     * 获取数据库中现存的留言列表
     * @return
     */
    @RequestMapping("/getList")
    public List<MassageInfo> getList(){
    return service.selectAll();
    };

    /**
     * 上传留言到列表
     * !!!参数列表中的参数接收JSON对象要通过@RequestBody 才能获取到值
     * @param massageInfo
     * @return
     */
    @RequestMapping(value="/publish",produces = "application/json")
    public String publish(@RequestBody MassageInfo massageInfo){
        if(massageInfo==null){
            log.error("上传失败!1");
            return "{\"ok\":0}";
        }
        if(!StringUtils.hasLength(massageInfo.getFrom())
                ||!StringUtils.hasLength(massageInfo.getMessage())
                ||!StringUtils.hasLength(massageInfo.getTo())){
            log.info(massageInfo.toString());
            log.error("上传失败!2");
            return "{\"ok\":0}";
        }
        try {
            Integer result=service.addMassage(massageInfo);
            log.info("上传成功!");
            return result==1 ? "{\"ok\":1}" : "{\"ok\":0}";
        }catch (Exception e){
            log.error("上传失败!3");
            return "{\"ok\":0}";
        }
    }


}
